<template>
  <div>
    <div class="topDiv">
      <div class="topL">
        <div class="logo">
          <a href="Home">
            <!-- 这两张图片点哪张都会跳转主页,但是把登录状态给忘记了 -->
            <img src="@/assets/images/LOGO.png" />
            <img src="@/assets/images/view_logo40.png" class="img1" />
          </a>
        </div>
        <img src="@/assets/images/spirit_40.png" />
      </div>
      <div class="topR">
        <div class="topR0 topR2">
          <!-- 注册和个人登录是不是不用在这个页面显示了 -->
          <a href="register.vue">注册</a>
        </div>
        <div class="topR0 topR3">
          <a href="login.vue">个人登录</a>
        </div>
        <div class="clear"></div>
      </div>
    </div>
    <div class="menuDiv">
      <div class="mainWarp"></div>
    </div>
    <div class="clear"></div>
    <div class="menuLittle"></div>
    <div class="clear"></div>

<!-- ---------------------------------------------------------------------------------- -->
<div class="search-container">
      <!-- 带有下拉菜单的输入框 -->
      <el-select
        v-model="selectedJob"
        placeholder="请输入职位名称"
        class="input-with-select"
        filterable
        allow-create
        default-first-option
        @change="onJobSelect"
      >
        <el-option
          v-for="job in jobOptions"
          :key="job.value"
          :label="job.label"
          :value="job.value"
        />
      </el-select>
      <!-- 搜索按钮 -->
      <el-button type="primary" @click="searchJobs" class="search-button">搜工作</el-button>
    </div>
<!-- ---------------------------------------------------------------------------------- -->

    <div class="clear"></div>
<!-- ----------------------------------------------------------------------------------- -->
<div class="seachlist">
    <!-- ****************************************** -->
  <div class="listtop">
  <div class="tj1">
    <!-- 点击list变false就不显示详细信息 -->
    <span class="list" @click="changeModeToList">列表</span>
    <!-- 点击摘要变true就显示详细信息 -->
    <span class="zhaoyao" @click="changeModeToSummery">摘要</span>
  </div>
    <!-- ***************************************** -->
    <div class="tj3">
      <span> 共{{ totalResults }}条 第{{ currentPage }}/{{ Math.ceil(totalResults / pageSize) }}页</span>
    </div>
  </div>
  <div class="clear"></div>
  <!-- 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888 -->
  <!-- 列表模式 -->
  <div class="listcon">
  <table border="0" width="100%" cellpadding="0" cellspacing="0" class="listtab">
    <thead>
      <tr>
        <th width="24%" style="padding-left: 17px">职位名称</th>
        <th width="30%">企业名称</th>
        <th width="16%">工作地点</th>
        <th width="8%">薪水</th>
        <th width="10%">刷新时间</th>
      </tr>
    </thead>
    <tbody>
      <template v-for="(job, index) in searchResults" :key="job.jobId">
        <!-- 基本信息行 -->
        <tr :class="{'stripe-even': (index % 2 === 0), 'stripe-odd': (index % 2 !== 0)}">
          <td>
            <a href="job_info.vue" class="jobname">{{ job.jobName }}</a>
          </td>
          <td>
            <div class="company">
              <a @click="goToCompany(job)">{{ job.enterpriseName }}</a>
            </div>
          </td>
          <td>{{ job.enterpriseAddress }}</td>
          <td><span>{{ job.minSalary }}K-{{ job.maxSalary }}K</span></td>
          <td>{{ formatRelativeTime(job.jobUpdateTime) }}</td>
        </tr>
        <!-- 详细信息行 -->
        <tr v-show="isSummery" :class="{'stripe-even': (index % 2 === 0), 'stripe-odd': (index % 2 !== 0)}" class="xxdetail">
          <td colspan="5">
            <div class="detail-container">
              <div class="yaoqiu">
                学历要求：{{ job.minDegree }} | 工作经验：{{ job.experience }} | 公司规模：{{ job.enterpriseSize }} | 招聘方式：{{ job.jobNature }}<br />
                岗位要求：<span class="job-details">{{ truncateText(job.jobDetails,75) }}</span>
              </div>
              <div class="applydiv">
                <a v-if="!isApplied(job.jobId)" @click="applyNow(job.jobId)" class="ljsqbtn">立即申请</a>
                <a v-else href="javascript:void(0);" class="ysqbtn">已申请</a>
                <span v-if="!isInterested(job.enterpriseId)" @click="interestNow(job.enterpriseId)" >关注</span>
                <span v-else href="javascript:void(0);" class="ygz">已关注</span>

              </div>
            </div>
          </td>
        </tr>
      </template>
    </tbody>
  </table>
</div>

  <!-- 88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888 -->
  <div class="clear"></div>
  <div class="listbottom">
    <div class="lb3">
      <span> 共{{ totalResults }}条 第{{ currentPage }}/{{ Math.ceil(totalResults / pageSize) }}页</span>
    </div>
  </div>
  <div class="clear"></div>
  <!-- ------------------------------------------------------------------------分页导航栏 -->
  <el-pagination
  background
  layout="prev, pager, next"
  :current-page="currentPage"
  :page-size="pageSize"
  :total="totalResults"
  @current-change="handlePageChange"
/>

</div>
    <!-- ----------------------------------------------------------------------------------- -->
    <div class="clear"></div>
    <div class="footer"></div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import { onMounted } from "vue";
import storageUtils from '@/util';
import router from '@/router'; // 确保引入了路由配置
import {getJobs,getJobNames,getApplyJobs,postApplyJob,getInterestedEnterprises,interestEnterprise} from '@/api/jobApplyInterest'

const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 固定每页显示 3 条数据
const totalResults = ref(0); // 总条数
const searchResults = ref([]); // 搜索结果
onMounted(() => {
  // 页面加载时自动获取全部职位
  searchJobs();
});

    const jobOptions = ref([]); // 动态职位选项

    // 绑定选中的职位
    const selectedJob = ref("");

    // 处理下拉菜单选中的事件
    const onJobSelect = (value) => {
      console.log("选中的职位：", value);
    };

    // 搜索工作逻辑-------------------------------------------------------------------
    // 搜索工作逻辑
const searchJobs = async () => {
  const keyword = selectedJob.value || ""; // 获取搜索关键词
  try {

    const response = await getJobs(keyword, currentPage.value, pageSize.value);

    // const response = await axios.get("/job/jobs", {
    //   params: {
    //     jobName: keyword, // 传递关键词
    //     page: currentPage.value, // 当前页码
    //     size: pageSize.value // 每页显示条数
    //   }
    // });

    if (response.data && response.data.code === 0) {
      const { total, items } = response.data.data;

      // 对每条数据进行转换
      items.forEach(transformJobData);

      searchResults.value = items; // 更新搜索结果
      totalResults.value = total; // 更新总条数
    } else {
      alert("搜索失败：" + response.data.message);
    }
  } catch (error) {
    console.error("搜索请求失败：", error);
    alert("请求失败，请稍后重试！");
  }
};

// 定义相对时间格式化函数
const formatRelativeTime = (timestamp) => {
  const now = new Date().getTime(); // 当前时间的时间戳（毫秒）
  const diff = now - timestamp; // 时间差（毫秒）

  const minute = 60 * 1000; // 1分钟的毫秒数
  const hour = 60 * minute; // 1小时的毫秒数
  const day = 24 * hour; // 1天的毫秒数

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`;
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`;
  } else {
    return `${Math.floor(diff / day)}天前`;
  }
};

// 分页页码变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  searchJobs(); // 重新请求数据
};
// ---------------------------------------------------------动态获得下拉菜单内容
// 获取职位列表的接口方法
const fetchJobOptions = async () => {
  try {
    const response = await getJobNames();
    if (response.data && response.data.code === 0) {
      //不重复，这块还得好好学学
      const uniqueJobs = [...new Set(response.data.data.map(job => job.jobName))];
      jobOptions.value = uniqueJobs.map(jobName => ({
        label: jobName,
        value: jobName
      }));
    } else {
      console.error("获取职位失败：", response.data.message);
    }
  } catch (error) {
    console.error("请求职位失败：", error);
  }
};

// 页面加载时获取职位列表
onMounted(() => {
  fetchJobOptions();
});

//*****************************************************列表和摘要的实现
const isSummery = ref(false);

function changeModeToSummery(){
  isSummery.value = true;
}
function changeModeToList(){
  isSummery.value = false;
}

//截取职位要求，只要一行，行尾三个点表示省略
const truncateText = (text, maxLength) => {
  if (text.length > maxLength) {
    return text.slice(0, maxLength) + '...';
  }
  return text;
};


const transformJobData = (job) => {
  // 转换学历要求
  const degreeMap = ["大专", "本科", "硕士", "博士"];
  job.minDegree = degreeMap[job.minDegree] || "未知";

  // 转换工作经验
  const experienceMap = ["有经验", "不限"];
  job.experience = experienceMap[job.experience] || "未知";

  // 转换公司规模
  const sizeMap = ["少于50人", "50-200人", "200人以上"];
  job.enterpriseSize = sizeMap[job.enterpriseSize - 1] || "未知";

  // 转换招聘方式
  const natureMap = ["全职", "兼职", "实习"];
  job.jobNature = natureMap[job.jobNature] || "未知";
};
// -------------------------------------------------------------------------立即申请和已申请----------
// 从 sessionStorage 获取当前登录用户的 userId
const userId = storageUtils.getSessionObject('loginUser').userId;

// 用来放申请过的职位的 id 的数组
const appliedJobIds = ref([]);

// 发请求去申请表
const fetchAppliedJobs = async () => {
  try {
    const response = await getApplyJobs(userId);
    // const response = await axios.get(`/apply/getAppliedJobs`, {
    //   params: { userId }
    // });

    // 检查后端返回的 code 是否为 0（成功）
    if (response.data && response.data.code === 0) {
      // 提取后端返回的职位数据
      const appliedJobs = response.data.data || [];
      appliedJobIds.value = appliedJobs.map(item => item.jobId); // 假设后端返回的字段是 jobId
      console.log(appliedJobs);
    } else {
      // 如果返回失败，打印错误信息
      console.error('获取申请记录失败：', response.data.message);
    }
  } catch (error) {
    // 网络请求失败或其他错误
    console.error('请求失败：', error);
  }
};

// 页面加载时调用 fetchAppliedJobs 方法
onMounted(() => {
  fetchAppliedJobs();
});

// 检查是否已申请
const isApplied = (jobId) => {
  return appliedJobIds.value.includes(jobId);
};

//点击立即申请，插入apply表
// 发送申请请求
const applyNow = async (jobId) => {
    const nowtime = new Date().toISOString();
  try {
    const response = await postApplyJob(userId, jobId,nowtime);
    // const response = await axios.post("/apply/applyJob", {
    //   userId: userId,
    //   jobId: jobId,
    //   updateTime: new Date().toISOString() // 发送当前时间
    // });

    if (response.data && response.data.code === 0) {
      appliedJobIds.value.push(jobId); // 添加到已申请列表
    } else {
      alert("申请失败：" + response.data.message);
    }
  } catch (error) {
    console.error("申请请求失败：", error);
    alert("请求失败，请稍后重试！");
  }
};
//*******************************************************************关注，已关注 */
// 用来放关注过的企业的 id 的数组
const interestedEnterpriseIds = ref(new Set());

// 发请求去获取已关注的企业
const fetchInterestedEnterprises = async () => {
  try {
    const response = await getInterestedEnterprises(userId);
    // const response = await axios.get("/interest/getInterestedEnterprises", {
    //   params: { userId }
    // });

    if (response.data && response.data.code === 0) {
      const interestedEnterprises = response.data.data || [];
      interestedEnterpriseIds.value = new Set(interestedEnterprises.map(item => item.enterpriseId));
    } else {
      console.error('获取关注记录失败：', response.data.message);
    }
  } catch (error) {
    console.error('请求失败：', error);
  }
};

// 页面加载时调用 fetchInterestedEnterprises 方法
onMounted(() => {
  fetchInterestedEnterprises();
});

// 检查是否已关注
const isInterested = (enterpriseId) => {
  return interestedEnterpriseIds.value.has(enterpriseId);
};

// 点击关注，插入 interest 表
const interestNow = async (enterpriseId) => {
  const nowtime = new Date().toISOString();
  try {
    const response = await interestEnterprise(userId, enterpriseId,nowtime);
    // const response = await axios.post("/interest/addInterest", {
    //   userId: userId,
    //   enterpriseId: enterpriseId,
    //   updateTime: new Date().toISOString()
    // });

    if (response.data && response.data.code === 0) {
      interestedEnterpriseIds.value.add(enterpriseId); // 添加到已关注列表
    } else {
      alert("关注失败：" + response.data.message);
    }
  } catch (error) {
    console.error("关注请求失败：", error);
    alert("请求失败，请稍后重试！");
  }
};

//点击企业名跳转企业详细信息
function goToCompany(job) {
  router.push({ name: 'company', params: { enterpriseId: job.enterpriseId } });
}
</script>

<style scoped>

@import '@/assets/css/searchJob.css';

</style>
<style scoped>

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.input-with-select {
  width: 500px; /* 调整输入框宽度 */
}

.search-button {
  padding: 5px 15px; /* 调整按钮大小 */
}


/*斑马纹 */
/* 偶数行的背景颜色 */
.listtab tbody tr.stripe-even {
  background-color: white;
  
}

/* 奇数行的背景颜色 */
.listtab tbody tr.stripe-odd {
  background-color: rgb(247, 248, 250);
}




.detail-container {
  display: flex;
  justify-content: space-between; /* 子元素之间的空间均匀分布 */
  align-items: center; /* 垂直居中对齐 */
}

.yaoqiu {
  flex: 1; /* 让摘要信息占据剩余空间 */
  white-space: nowrap; /* 防止换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.applydiv {
  margin-left: 20px; /* 与摘要信息保持一定距离 */
}

a {
  cursor: pointer; /* 确保鼠标指针是手形 */
}
span {
  cursor: pointer; /* 确保鼠标指针是手形 */
}


</style>

